(function($, im, chat, doc) {
	var userinfo = app.getState();
	im.record = [];
	//im.ws = new WebSocket(chaturl);
	//var ws;

	im.bindMsgList = function() {
		//定义传递给模板的变量
		if(im.record.length < 1) {
			im.areaMsgList.innerHTML = template('msg-template', {
				"record": im.record,
				"header": im.header
			});
		} else {
			im.areaMsgList.innerHTML = im.areaMsgList.innerHTML + template('msg-template', {
				"record": im.record,
				"header": im.header
			});

		}
		/*
		var msgItems = im.areaMsgList.querySelectorAll('.msg-item');
		[].forEach.call(msgItems, function(item, index) {
			item.addEventListener('tap', function(event) {
				msgItemTap(item, event);
			}, false);
		});*/
		im.imageViewer.findAllImage();
		im.areaMsgList.scrollTop = im.areaMsgList.scrollHeight + im.areaMsgList.offsetHeight;
	};
	im.getId = function() {
		return im.uid + '-'+im.roomId + '-' + Date.parse(new Date());
	};
	im.parseChatData = function(data) {
		var cache = [];
		for(var p in data) {
			var val = data[p];
			if(val['f_header'] && val['f_header'].indexOf('upload/') !== -1) {
				var header = serverurl + 'upload/avatar/' + val['f_id'] + '.jpg';
			} else {
				var header = '../../static/images/1.png';
			}
			if(val['f_id'] == im.uid) {
				val['f_id'] = 'self';
			}
			var pashdata = {
				mid: p,
				header: header,
				name: val['f_name'],
				sender: val['f_id'],
				type: val['r_type'],
				content: val['t_msg'],
				add_time: val['add_time'],
				time: app.dateStr(val['add_time']),
				extras: val['extras'] ? JSON.parse(val['extras']) : {}
			};
			im.record.push(pashdata);
			cache.push(pashdata);
		}
		return cache;
	}

	function initServiceData() {
		var keys = im.uid + '_' + im.roomId;
		//plus.storage.removeItem(keys);
		var data = plus.storage.getItem(keys);
		//console.log(JSON.stringify(data));
		var geturl = apiurl + 'chat/getlist?user_id=' + im.uid + '&fid=' + im.roomId + '&ctype=' + im.roomType;
		if(!data) {
			var data = {};
			$.get(geturl, function(res) {
				if(res && res.status && res.list && res.list.length > 0) {
					var list = res.list,
						i = 0,
						len = list.length;
					for(; i < len; i++) {
						var v = list[i],
							k = v['id'];
						data[k] = v;
					}
					plus.storage.setItem(keys, JSON.stringify(data));
					//parseChatData(data);
				}
			});
		} else {
			//console.log();
			var data = app.isJson(data) ? JSON.parse(data) : app.strToJson(data);
			var lastkey;
			for(var p in data) {
				lastkey = p;
			}
			var m_id = data[lastkey]['m_id'];
			if(m_id > 0) {
				var geturl = geturl + '&lastid=' + m_id;
				//console.log(geturl);
				$.get(geturl, function(res) {
					if(res && res.status && res.list && res.list.length > 0) {
						var list = res.list,
							i = 0,
							len = list.length;
						for(; i < len; i++) {
							var v = list[i],
								k = v['id'];
							data[k] = v;
						}
						plus.storage.setItem(keys, JSON.stringify(data));
					}
				});
			}

		}

	};
	//添加或更新本地数据
	im.addOrUpdateserviceData = function(msgInfo) {
		var keys = im.uid + '_' + im.roomId;
		var data = plus.storage.getItem(keys);
		if(data) {
			var parsedata = app.isJson(data) ? JSON.parse(data) : app.strToJson(data);
		}else{
			var parsedata = {};
		}
		var id = msgInfo['id'];
		parsedata[id] = msgInfo;
		plus.storage.setItem(keys, JSON.stringify(parsedata));
	};
	
	//分页
	im.currentpage = 1;
	im.pagenum = 1;
	im.pageMgr = function(data) {
		var pagesize = 20,
			pagenum = 1,
			allnum = 0,
			cache = {};
		for(var p in data) {
			//cache.push(data[p]);
			allnum++;
		}
		im.pagenum = Math.ceil(allnum / pagesize); //向上取整,有小数就整数部分加1
		if(allnum < pagesize || im.pagenum == 1) {
			return data;
		}

		if(im.currentpage >= im.pagenum) {
			var breaknum = 0;
			var endnum = im.pagenum * pagesize - allnum;
		} else {
			var breaknum = allnum - im.currentpage * pagesize;
			var endnum = breaknum + pagesize;
		}
		//console.log(breaknum);
		//console.log(endnum);
		if(breaknum >= 0) {
			var i = 0;
			for(var p in data) {
				i++;
				if(i > breaknum && i <= endnum) {
					cache[p] = data[p];
				}
			}
			//console.log(JSON.stringify(cache));
			return cache;
		} else {
			console.log('error');
			return {};
		}

	};

	im.getDatas = function() {
		var data = plus.storage.getItem(im.uid + '_' + im.roomId);
		var parsedata = app.isJson(data) ? JSON.parse(data) : app.strToJson(data);
		return im.pageMgr(parsedata);
		//return parsedata;
	}

	im.getServiceData = function() {
		initServiceData();
		parsedata = im.getDatas();
		im.parseChatData(parsedata);
		im.bindMsgList();
	}

	im.showKeyboard = function() {
		if($.os.ios) {
			var webView = plus.webview.currentWebview().nativeInstanceObject();
			webView.plusCallMethod({
				"setKeyboardDisplayRequiresUserAction": false
			});
		} else {
			var Context = plus.android.importClass("android.content.Context");
			var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
			var main = plus.android.runtimeMainActivity();
			var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
			//var view = ((ViewGroup)main.findViewById(android.R.id.content)).getChildAt(0);
			imm.showSoftInput(main.getWindow().getDecorView(), InputMethodManager.SHOW_IMPLICIT);
			//alert("ll");
		}
	};
	im.sendMsg = function(msg) {
		//im.record.push(msg);
		//chat.venderToIndex(msg.content, msg.type, 1);

		var msgInfo = {
			type: 'say',
			id: im.getId(),
			user_id: im.uid,
			user_name: userinfo.name,
			user_header: userinfo.avatar ? userinfo.avatar : '',
			room_id: im.roomId,
			chat_name: im.chatName,
			header: im.header,
			msg: msg.content,
			ftype: msg.type, //聊天类型
			ctype: im.roomType, //聊天室类型
			extras: msg.extras || {}

		};
		//im.bindMsgList();

		im.addnewMsg(msgInfo);
		im.sendnewMsg(msgInfo);
		im.toRobot(msgInfo);
	};

	//var mainWin = plus.webview.getWebviewById(mainid);
	im.toRobot = function(msgInfo) {

		mui.fire(im.mainWin, 'sendMsg', msgInfo);
		//main.evalJS("ws.send('"+JSON.stringify(msgInfo)+"')"); 
		/*
		mui.post(toUrl, msgInfo, function(res){
			if(!res.status) {
				mui.alert('发送失败！');
			}else{
				localStorage.setItem('newmsg', res.cid);
			}
		});*/
	};
	im.loginroom = function() {
		userinfo.type = 'loginroom';
		userinfo.roomId = im.roomId;
		userinfo.ctype = im.roomType;
		mui.fire(im.mainWin, 'loginroom', userinfo);
	}

	/**
	 * 我发消息,更新列表页和聊天页
	 * @param {Object} msgInfo
	 */
	im.addnewMsg = function(msgInfo) {
		
		//console.log();
		im.addOrUpdateserviceData(msgInfo);
		var rtinfo = {
			id: msgInfo.id,
			f_id: msgInfo.room_id,
			f_name: msgInfo.chat_name,
			f_header: msgInfo.header,
			t_header: msgInfo.user_header,
			t_name: msgInfo.user_name,
			t_msg: msgInfo.msg,
			t_id: msgInfo.user_id,
			ctype: im.roomType,
			r_type: msgInfo.ftype,
			isread : 0,
			m_id : 0,
			add_time: Date.parse(new Date()) / 1000
		};
		//更新列表
		chat.updateSay(rtinfo, im.data_type);
	};

	/**
	 * 发送消息 
	 * @param {Object} msgInfo
	 */
	im.sendnewMsg = function(msgInfo) {
		var msg = {
			sender: msgInfo.user_id == im.uid ? 'self' : msgInfo.user_id,
			type: msgInfo.ftype,
			content: msgInfo.msg,
			add_time: msgInfo.add_time || Date.parse(new Date()) / 1000,
			time: app.dateStr(Date.parse(new Date()) / 1000),
			extras: msgInfo.extras
		};
		im.record.push(msg);
		im.bindMsgList();
	}

	function rendernewMsg(msg) {
		var tpl = template('msg-template', {
			"record": [msg],
			"header": im.header
		});
		im.areaMsgList.appendChild(tpl);
	}
	//侦听主窗口 我收消息
	window.addEventListener('refreshSay', function(event) {
		var rtinfo = event.detail;
		var fid = rtinfo['f_id'];
		//console.log(JSON.stringify(rtinfo));
		//console.log(im.roomId);
		im.addOrUpdateserviceData(rtinfo);
		if(im.roomType == 1) {
			//是自己
			if(fid != im.roomId) {
				return;
			}
			var header = rtinfo['f_header'] ? serverurl + 'upload/avatar/' + fid + '.jpg' : '../../static/images/logo.png';
			var emsg = {
				id : reinfo['id'],
				header: header,
				sender: rtinfo['f_id'],
				type: rtinfo['r_type'],
				content: rtinfo['t_msg'],
				time: app.dateStr(rtinfo['add_time']),
				extras: rtinfo['extras'] ? JSON.parse(rtinfo['extras']) : {}
			};
			//im.record.push(emsg);
			//im.bindMsgList();
		} else {
			if(rtinfo['t_id'] != im.roomId) {
				return;
			}
			//是自己
			if(rtinfo['f_id'] == im.uid) {
				return;
			}
			var header = rtinfo['f_header'] ? serverurl + 'upload/avatar/' + fid + '.jpg' : '../../static/images/qun.jpg';
			var emsg = {
				id : reinfo['id'],
				header: header,
				name: rtinfo['f_name'],
				sender: fid,
				type: rtinfo['r_type'],
				content: rtinfo['t_msg'],
				time: app.dateStr(rtinfo['add_time']),
				extras: rtinfo['extras'] ? JSON.parse(rtinfo['extras']) : {}
			};
			chat.setDataByField(im.roomId, 'msgnum', 0, 'room');

		}
		im.record.push(emsg);
		im.bindMsgList();

	});
	im.resizeMsgList = function() {
		im.areaMsgList.scrollTop = im.areaMsgList.scrollHeight + im.areaMsgList.offsetHeight;
	};

	//window.im = im; 

	$.plusReady(function() {
		im.body = doc.querySelector('body');
		im.footer = doc.querySelector('footer');
		im.footerRight = doc.querySelector('.footer-left');
		im.footerLeft = doc.querySelector('.footer-right');
		im.btnMsgImage = doc.querySelector('#msg-type');
		im.boxMsgText = doc.querySelector('#msg-text');
		im.boxMsgSound = doc.querySelector('#msg-sound');
		im.btnMsgType = doc.querySelector('#msg-image');
		im.areaMsgList = doc.querySelector('#msg-list');
		im.boxSoundAlert = doc.querySelector('#sound-alert');
		im.h = doc.querySelector('#h');
		im.content = doc.querySelector('.mui-content');
		im.uid = userinfo.user_id; //我的 id
		im.user_name = userinfo.name;
		im.chat = chat;

		im.page = 1;
		var mainid = localStorage.getItem('mainpage');
		im.mainWin = plus.webview.getWebviewById(mainid);

		//im.ws = null;
		im.isios = mui.os.ios ? true : false;
		im.header = plus.webview.currentWebview().chatHeader;
		im.chatName = plus.webview.currentWebview().chatTitle;
		im.roomType = plus.webview.currentWebview().roomType;
		im.roomId = plus.webview.currentWebview().roomId; //说话对象
		im.extraWin = {
			chatHeader: im.header,
			chatTitle: im.chatName,
			roomType: im.roomType,
			roomId: im.roomId
		};

		//newmsg
		im.tomsgtype = plus.webview.currentWebview().tomsgtype;
		im.tomsgsender = plus.webview.currentWebview().tomsgsender;
		im.tomsgcontent = plus.webview.currentWebview().tomsgcontent;
		if(userinfo.avatar && userinfo.avatar.indexOf('upload') !== -1) {
			im.header = serverurl + 'upload/avatar/' + im.uid + '.jpg';
		} else {
			im.header = '../../static/images/logo.png';
		}
		im.imageViewer = new $.ImageViewer('.msg-content-image', {
			dbl: false
		});
		if(im.roomType == 1) {
			im.data_type = 'index';
		} else {
			im.data_type = 'room';
		}
		if(im.tomsgsender) {
			var sendmsg = {
				sender: im.tomsgsender,
				type: im.tomsgtype,
				content: im.tomsgcontent
			};
			im.record.push(sendmsg);
			im.bindMsgList();
		}
		$.init({
			swipeBack: true,
			gestureConfig: {
				tap: true, //默认为true
				doubletap: true, //默认为false
				longtap: true, //默认为false
				swipe: true, //默认为true
				drag: true, //默认为true
				hold: true, //默认为false，不监听
				release: true //默认为false，不监听
			},
			beforeback: function() {
				//关闭时候的一些操作
				//socket.onclose();
				//获得列表界面的webview  
				//var list = plus.webview.currentWebview().opener();
				if(im.roomType == 1) {
					var list = plus.webview.getWebviewById('chat.html');
				} else {
					var list = plus.webview.getWebviewById('room.html');
				}
				//触发列表界面的自定义事件（refresh）,从而进行数据刷新  
				mui.fire(list, 'refreshList');
				//返回true，继续页面关闭逻辑  
				return true;
			},
			/*pullRefresh: {
				container: "#msg-list", //下拉刷新容器标识，querySelector能定位的css选择器均可，比如：id、.class等
				down : {
			      style:'circle',//必选，下拉刷新样式，目前支持原生5+ ‘circle’ 样式
			      color:'#2BD009', //可选，默认“#2BD009” 下拉刷新控件颜色
			      height:'50px',//可选,默认50px.下拉刷新控件的高度,
			      range:'100px', //可选 默认100px,控件可下拉拖拽的范围
			      offset:'60px', //可选 默认0px,下拉刷新控件的起始位置
			      auto: false,//可选,默认false.首次加载自动上拉刷新一次
			      callback :dragpage //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
			    }
			}*/
		});

		document.querySelector('.mui-title').innerHTML = im.chatName;
		if(im.uid == im.roomId) {
			mui.alert('你不能给自己聊天');
			mui.back();
		}
		plus.webview.currentWebview().setStyle({
			softinputMode: "adjustResize"
		});
		template.config('escape', false);
		im.h.style.width = im.boxMsgText.offsetWidth + 'px';
		//alert(ui.boxMsgText.offsetWidth );
		im.footerPadding = im.footer.offsetHeight - im.boxMsgText.offsetHeight;

		im.getServiceData();
		chat.setDataByField(im.roomId, 'msgnum', 0, im.data_type);
		im.loginroom();
		window.addEventListener('resize', im.resizeMsgList, false);
		//var my = plus.webview.getSecondWebview();
		//console.log(JSON.stringify(my)); 
		//im.connect();

	});

}(mui, window.im = {}, chat, document));